#include "stdafx.h"
#include "truetype_hmtx.h"
#include "truetype.h"

void truetype_hmtx(truetype_t * tt, tt_table_t * table)
{
	if(!tt || !tt->stream || !table || table->type != tt_table_type_hmtx)
		return ;
	base_stream_t * stream = tt->stream;

	tt_hmtx_t * hmtx = &tt->hmtx;

	uint_32 length = hmtx->base_count * sizeof(tt_hmtx_info_t);
	tt_hmtx_info_t * hmtx_info = (tt_hmtx_info_t *)truetype_malloc(length);
	hmtx->base_info = hmtx_info;

	stream->seeker(stream, table->offset, stream_seek_begin);
	stream->reader(stream, hmtx_info, length);

#ifdef TT_SMALL_ENDIAN
	for(uint_32 cnt = 0; cnt != hmtx->base_count; ++cnt, ++hmtx_info)
	{
		hmtx_info->ad_width = confirm_big_word(hmtx_info->ad_width);
		hmtx_info->lsb = confirm_big_word(hmtx_info->lsb);
	}
#endif // TT_SMALL_ENDIAN

	hmtx->extern_count = tt->glyf_count - hmtx->base_count;
	if(hmtx->extern_count)
	{
		if((uint_32)hmtx->extern_count << 1 > table->length - length)
			hmtx->extern_count = (table->length - length) >> 1;

		length = hmtx->extern_count << 1;
		hmtx->lsb_ex = (int_16 *)truetype_malloc(length);
		stream->reader(stream, hmtx->lsb_ex, length);
#ifdef TT_SMALL_ENDIAN
		for(uint_32 cnt = 0; cnt != hmtx->extern_count; ++cnt)
			hmtx->lsb_ex[cnt] = confirm_big_word(hmtx->lsb_ex[cnt]);

#endif // TT_SMALL_ENDIAN
	}
	else
	{
		hmtx->extern_count = 0;
		hmtx->lsb_ex = 0;
	}
}

void truetype_hmtx_get_hmtx(truetype_t * tt, tt_glyf_index_t * index, tt_glyf_t * glyf)
{
	tt_hmtx_t * hmtx = &tt->hmtx;
	if(index->loca_index < hmtx->base_count)
	{
		glyf->ad_width = hmtx->base_info[index->loca_index].ad_width;	
		glyf->lsb = hmtx->base_info[index->loca_index].lsb;	
	}
	else if(index->loca_index >= hmtx->base_count && index->loca_index < hmtx->base_count + hmtx->extern_count)
	{
		glyf->ad_width = hmtx->base_info[hmtx->base_count - 1].ad_width;	
		glyf->lsb = hmtx->lsb_ex[index->loca_index - hmtx->base_count];	
	}
	else
	{
		glyf->ad_width = hmtx->base_info[0].ad_width;	
		glyf->lsb = hmtx->base_info[0].lsb;	
	}
}